/**
1. 状态控制：
   1. state: 'PENDING' 等待态   'FULFILLED'  成功态 'REJECTED'  失败态
   2. method: executor / then (内部函数 resolve / reject / onFulfilled / onRejected ）
   3. props：value / reason
   4. 特点：
      1. 状态不可二次修改，二次修改则报错
      2. then方法根据promise状态执行对应回调
2. 异步订阅发布
*/
class FakePromise {
  state = "PENDING";
  value;
  reason;
  constructor(executor) {
    let resolve = (value) => {
      if (this.state === "PENDING") {
        this.state = "FULFILLED";
        this.value = value;
      } else {
        throw new Error("promise state is not PENDING");
      }
    };
    let reject = (reason) => {
      if (this.state === "PENDING") {
        this.state = "REJECTED";
        this.reason = reason;
      } else {
        throw new Error("promise state is not PENDING");
      }
    };
    // executor 执行的时候 需要传入两个参数，给用户来改变状态的
    try {
      executor(resolve, reject);
    } catch (e) {
      // 表示当前有异常，那就使用这个异常作为promise失败的原因
      reject(e);
    }
  }
  then(onFulfilled, onRejected) {
    if (this.state === "FULFILLED") {
      onFulfilled(this.value);
    }
    if (this.state === "REJECTED") {
      onRejected(this.reason);
    }
  }
}
let p = new FakePromise((resolve, reject) => {
  reject("reason");
  resolve("value");
  //   throw new Error("我失败了");
});

p.then(
  (success) => {
    console.log("success", success);
  },
  (err) => {
    console.log("fail", err);
  }
);
